package com.sgl.config.shiro;

import com.sgl.dao.UserMapper;
import com.sgl.entity.User;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class UserRealm extends AuthorizingRealm {
	
	@Autowired
	private UserMapper userMapper;
	
    /**
     * 授权(验证权限时调用)
     */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		
		User user = (User)principals.getPrimaryPrincipal();
		info.addRole(user.getRole().toString());
		return info;
	}
	/**
	 * 认证(登录时调用)
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken authcToken) throws AuthenticationException {
		UsernamePasswordToken token = (UsernamePasswordToken)authcToken;
		
		User user = userMapper.findByBgLoginName(token.getUsername());
		if(user == null) {
			return null;
		}
		if(user.getRole().intValue() == 0) {
			throw new IncorrectCredentialsException();
		}
		if(user.getStatus().intValue() == 1) {
			throw new IncorrectCredentialsException();
		}
		SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, user.getBgPassword(), ByteSource.Util.bytes(user.getBgSalt()), getName());
		return info;
	}
	@Override
	public void setCredentialsMatcher(CredentialsMatcher credentialsMatcher) {
		HashedCredentialsMatcher shaCredentialsMatcher = new HashedCredentialsMatcher();
		shaCredentialsMatcher.setHashAlgorithmName(ShiroUtil.hashAlgorithmName);
		shaCredentialsMatcher.setHashIterations(ShiroUtil.hashIterations);
		super.setCredentialsMatcher(shaCredentialsMatcher);
	}
	
}
